package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.article.domain.Huida;
import cn.wolfcode.luowowo.article.domain.HuidaContent;
import cn.wolfcode.luowowo.article.domain.Wenda;
import cn.wolfcode.luowowo.article.mapper.HuidaContentMapper;
import cn.wolfcode.luowowo.article.mapper.HuidaMapper;
import cn.wolfcode.luowowo.article.mapper.WendaMapper;
import cn.wolfcode.luowowo.article.query.HuidaQuery;
import cn.wolfcode.luowowo.article.service.IHuidaService;
import cn.wolfcode.luowowo.article.vo.DetailVO;
import cn.wolfcode.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
@Service
public class HuidaServiceImpl implements IHuidaService {
    @Autowired
    private HuidaMapper huidaMapper;
    @Autowired
    private HuidaContentMapper huidaContentMapper;
    @Autowired
    private WendaMapper wendaMapper;

    @Override
    public Huida get(Long id) {
        return huidaMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Huida> selectByWendaId(Long wendaId) {
        return huidaMapper.selectByWendaId(wendaId);
    }

    @Override
    public PageInfo query(HuidaQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        return new PageInfo(huidaMapper.selectForList(qo));
    }

    @Override
    public void saveOrUpdate(Huida huida) {
        if (huida.getContent() == null){
            throw new LogicException("回答不能为空");
        }
        if(huida.getId() == null){
            huida.setCreateTime(new Date());
            huida.setCoverUrl("/902397dda144ad34bc15c9f4dda20cf431ad851f.jpg");
            HuidaContent content = huida.getContent();
            String stringC = content.getContent();
            if (stringC.length() < 100){
                huida.setSummary(stringC);
            } else {
                huida.setSummary(stringC.substring(0, 100));
            }
            huidaMapper.insert(huida);
            content.setId(huida.getId());
            huidaContentMapper.insert(content);
            Wenda wenda = huida.getWenda();
            wenda.setAddReplynum(1);
            wendaMapper.updateNum(wenda);
        }else {
            huidaMapper.updateByPrimaryKey(huida);
            HuidaContent content = huida.getContent();
            content.setId(huida.getId());
            huidaContentMapper.updateByPrimaryKey(content);
        }
    }

    @Override
    public void delete(Long id) {
        huidaMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateStatisByVo(DetailVO detailVO) {
        huidaMapper.updateStatisByVo(detailVO);
    }
}
